package com.example.Holo.uiactivities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.*;
import com.astuetz.PagerSlidingTabStrip;
import com.example.Holo.R;
import com.example.Holo.core.BaseApplication;
import com.example.Holo.rework.core.Friend;
import com.example.Holo.rework.core.Part;
import com.example.Holo.rework.core.Payment;
import com.example.Holo.rework.services.interfaces.IPartService;
import com.example.Holo.rework.services.interfaces.IServiceFactory;
import com.example.Holo.uiactivities.fragments.BaseFragment;
import com.example.Holo.uiactivities.fragments.ExpensesFragment;
import com.example.Holo.uiactivities.fragments.FriendsFragment;
import com.example.Holo.uiactivities.fragments.PayBackFragment;
import com.example.Holo.uiactivities.fragments.expensefragment.FriendsPayment;
import com.example.Holo.uiactivities.fragments.expensefragment.MvcModel;
import com.example.Holo.uiactivities.fragments.expensefragment.NewExpenseFragment;

import java.util.ArrayList;
import java.util.List;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;
import static android.util.TypedValue.applyDimension;
import static com.example.Holo.parameters.IntentConstants.*;

public class WorkingActivity extends FragmentActivity {

    private BaseFragment currentFragment;
    private ViewPager pager;

    private MyPagerAdapter pagerAdapter;
    private BaseApplication baseApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseApplication = (BaseApplication) getApplicationContext();
        setContentView(R.layout.working_activity);
        final Bundle extras = getIntent().getExtras();
        setTitle(extras.getString(NAME));
        baseApplication.setEventId(extras.getLong(ID));
        final PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);
        pager.setCurrentItem(1);

        final int pageMargin = (int) applyDimension(COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setViewPager(pager);
        tabs.setOnPageChangeListener(listener);
        tabs.setTextColor(Color.rgb(255, 255, 255));
        tabs.setIndicatorColor(Color.parseColor("#FF96AA39"));
        currentFragment = (BaseFragment) pagerAdapter.getItem(1);
    }

    private final EmptyTabChangeListener listener = new EmptyTabChangeListener() {
        @Override
        public void onPageSelected(int position) {
            currentFragment = (BaseFragment) pagerAdapter.getItem(position);
            currentFragment.onFragmentIsOnFocus();
            invalidateOptionsMenu();
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final int menuItem = currentFragment == null ? R.menu.empty_menu : currentFragment.getActivityMenuResource();
        getMenuInflater().inflate(menuItem, menu);
        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            final ArrayList<String> selectedFriends = data.getStringArrayListExtra(NAMES);
            final List<Friend> friends = convertToFriendObjects(selectedFriends);
            ((FriendsFragment) currentFragment).addFriendsAndUpdateView(friends);
        }
    }

    private List<Friend> convertToFriendObjects(ArrayList<String> names) {
        final List<Friend> friends = new ArrayList<Friend>();
        for (String name : names) {
            friends.add(new Friend(0, name));
        }
        return friends;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_friend_button:
                final Intent intent = new Intent(this, PickFriendsActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.add_expense_button:
                pagerAdapter.replace();
                break;
            case R.id.save_expense_button:
                final IServiceFactory serviceFactory = baseApplication.getServiceFactory();
                final IPartService partService = serviceFactory.createPartService();
                final List<FriendsPayment> friendPayments = ((NewExpenseFragment) currentFragment).friendPayments;
                final MvcModel mvcModel = ((NewExpenseFragment) currentFragment).mvcModel;
                final List<Part> parts = generateParts(mvcModel, friendPayments);
                final Payment payment = generatePayment(baseApplication.getEventId(), mvcModel);
                partService.addPayment(payment, parts);
                pagerAdapter.replace();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private Payment generatePayment(long eventId, MvcModel mvcModel) {
        return new Payment()
                .setEventId(eventId)
                .setName(mvcModel.getPaidFriendName() + " paid")
                .setPaidPersonId(mvcModel.getPaidFriendId())
                .setQuantity(mvcModel.getPaymentQuantity());
    }

    private List<Part> generateParts(MvcModel mvcModel, List<FriendsPayment> friendPayments) {
        final List<Part> parts = new ArrayList<Part>();
        for (FriendsPayment friendsPayment : friendPayments) {
            final Part part = new Part()
                    .setPaidPersonId(mvcModel.getPaidFriendId())
                    .setForWhomPaidPersonId(friendsPayment.friend.id)
                    .setQuantity(friendsPayment.getQuantity());
            parts.add(part);
        }
        return parts;
    }

    @Override
    public void onBackPressed() {
        if(pager.getCurrentItem() == 0) {
            if (pagerAdapter.getItem(0) instanceof NewExpenseFragment) {
                pagerAdapter.replace();
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    public class MyPagerAdapter extends FragmentStatePagerAdapter {

        private final String[] titles = {"Expenses", "Friends", "Pay back"};
        public Fragment mFragmentAtPos0;

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if (mFragmentAtPos0 == null)
                    {
                        mFragmentAtPos0 = new ExpensesFragment();
                    }
                    return mFragmentAtPos0;
                case 1:
                    return new FriendsFragment();
                case 2:
                    return new PayBackFragment();
            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof ExpensesFragment && mFragmentAtPos0 instanceof NewExpenseFragment) {
                return POSITION_NONE;
            }
            if (object instanceof NewExpenseFragment && mFragmentAtPos0 instanceof ExpensesFragment) {
                return POSITION_NONE;
            }
            return POSITION_UNCHANGED;
        }

        public void replace() {
            getSupportFragmentManager().beginTransaction().remove(mFragmentAtPos0).commit();
            if (mFragmentAtPos0 instanceof ExpensesFragment){
                mFragmentAtPos0 = new NewExpenseFragment();
            }else{
                mFragmentAtPos0 = new ExpensesFragment();
            }
            currentFragment = (BaseFragment) mFragmentAtPos0;
            invalidateOptionsMenu();
            notifyDataSetChanged();
        }
    }
}
